package socket;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/** 客户端 */
public class Client3 {
    private Socket socket;
    public Client3() {
        try {
            System.out.println("正在连接服务端...");
            socket = new Socket("176.61.4.11",8088);
            System.out.println("连接服务端成功!");

            ClientHandler clientHandler = new ClientHandler(socket);
            Thread t = new Thread(clientHandler);
            t.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start3(){
        try {
            OutputStream os = socket.getOutputStream();//低级流
            OutputStreamWriter osw = new OutputStreamWriter(os, StandardCharsets.UTF_8);
            BufferedWriter bw = new BufferedWriter(osw);
            PrintWriter pw = new PrintWriter(bw,true);

            Scanner sc = new Scanner(System.in);
            while (true){
                String line = sc.nextLine();
                pw.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public class ClientHandler implements Runnable{
        private Socket socket;
        private String host;

        public ClientHandler(Socket socket) {
            this.socket = socket;
            //通过sockst获取远端计算机的IP地址的字符串格式
            host = socket.getInetAddress().getHostAddress();
        }

        public void run() {
            try {
                InputStream is = socket.getInputStream();//低级流
                InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);

                String line;
                while ((line= br.readLine())!=null){
                    System.out.println(host+"说:"+line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Client3 client3 = new Client3();
        client3.start3();
    }
}
